﻿/*
Copyright (c) 2011 <a href="http://www.gutgames.com">James Craig</a>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#region Usings
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using ObjectCartographer.Interfaces;
using ObjectCartographer.Mappings.Attributes;
using ObjectCartographer.Mappings.DataClasses;
#endregion

namespace ObjectCartographer.Mappings
{
    /// <summary>
    /// Factory mapping
    /// </summary>
    /// <typeparam name="Source">Source type</typeparam>
    public class FactoryMapping<Source>:IMapping
    {
        #region Constructor

        /// <summary>
        /// Constructor
        /// </summary>
        public FactoryMapping()
        {
            Setup();
        }

        #endregion

        #region IMapping Members

        public Type SourceType
        {
            get { return typeof(Source); }
        }

        public Type DestinationType
        {
            get { return typeof(List<object>); }
        }

        public int NumberObjectsExpected()
        {
            return PropertyMappings.Count;
        }

        public void Sync(object Source, object Destination)
        {
            List<object> TempDestination = (List<object>)Destination;
            TempDestination=SourceMapping.GetNonDescriptions(TempDestination);
            int x = 0;
            foreach (MappingInfo PropertyMapping in PropertyMappings)
            {
                PropertyInfo PropertyInfo = null;
                object TempSourceObject = Utilities.Reflection.Reflection.GetPropertyParent(Source, PropertyMapping.Source, out PropertyInfo);
                if (PropertyInfo.PropertyType.Name == "List`1")
                {
                    object ValueObject = Utilities.Reflection.Reflection.GetPropertyValue(Source, PropertyMapping.Source);
                    Type ValueObjectType=Utilities.Reflection.Reflection.GetPropertyType(Source, PropertyMapping.Source);
                    Utilities.Reflection.Reflection.SetValue(ValueObjectType.Assembly.CreateInstance(ValueObjectType.FullName), Source, PropertyMapping.Source, "");
                    ValueObject = Utilities.Reflection.Reflection.GetPropertyValue(Source, PropertyMapping.Source);
                    MethodInfo AddMethod = ValueObjectType.GetMethod("Add");
                    List<object> TempDestinationList = (List<object>)TempDestination[x];
                    TempDestinationList=SourceMapping.GetNonDescriptions(TempDestinationList);
                    int ItemsExpected = Manager.Instance.NumberObjectsExpected(ValueObjectType.GetGenericArguments()[0], typeof(List<object>));
                    int y = 1;
                    List<object> SyncList = new List<object>();

                    PropertyInfo IndexProperty = ValueObjectType.GetProperty("Item");
                    PropertyInfo CountProperty = ValueObjectType.GetProperty("Count");
                    int Count = (int)CountProperty.GetValue(ValueObject, null);
                    Count = Count - 1;
                    foreach (object TempDestination2 in TempDestinationList)
                    {
                        SyncList.Add(TempDestination2);
                        if (y % ItemsExpected == 0)
                        {
                            object Value = null;
                            if (Count >= 0)
                            {
                                Value = IndexProperty.GetValue(ValueObject, new object[] { Count });
                            }
                            if (Value == null)
                            {
                                Value = ValueObjectType.GetGenericArguments()[0].Assembly.CreateInstance(ValueObjectType.GetGenericArguments()[0].FullName);
                            }
                            Manager.Instance.Sync(Value, SyncList);
                            if (Count < 0)
                            {
                                AddMethod.Invoke(ValueObject, new object[] { Value });
                            }
                            SyncList = new List<object>();
                            --Count;
                        }
                        ++y;
                    }
                }
                else
                {
                    SourceMapping.Sync(TempSourceObject, PropertyInfo, TempDestination[x]);
                }
                ++x;
            }
        }

        public object Create(object Source)
        {
            List<object> ReturnList = new List<object>();
            foreach (MappingInfo PropertyMapping in PropertyMappings)
            {
                if (!string.IsNullOrEmpty(PropertyMapping.Description))
                {
                    ReturnList.Add(SourceMapping.CreateDescription(PropertyMapping.Description));
                }
                Type PropertyType = Utilities.Reflection.Reflection.GetPropertyType(Source, PropertyMapping.Source);
                if (PropertyType.Name == "List`1")
                {
                    object ValueObject=Utilities.Reflection.Reflection.GetPropertyValue(Source,PropertyMapping.Source);
                    if (ValueObject != null)
                    {
                        List<object> TempReturnList = new List<object>();
                        Type ListType = ValueObject.GetType();
                        PropertyInfo IndexProperty = ListType.GetProperty("Item");
                        PropertyInfo CountProperty = ListType.GetProperty("Count");
                        int Count = (int)CountProperty.GetValue(ValueObject, null);
                        for (int x = 0; x < Count; ++x)
                        {
                            object Value = IndexProperty.GetValue(ValueObject, new object[] { x });
                            TempReturnList.AddRange((List<object>)Manager.Instance.Create(Value));
                        }
                        ReturnList.Add(TempReturnList);
                    }
                }
                else
                {
                    ReturnList.Add(SourceMapping.CreateDestination(Utilities.Reflection.Reflection.GetPropertyValue(Source, PropertyMapping.Source),
                        Utilities.Reflection.Reflection.GetPropertyType(Source, PropertyMapping.Source)));
                }
            }
            return ReturnList;
        }

        #endregion

        #region Protected Functions

        /// <summary>
        /// Maps source property
        /// </summary>
        /// <param name="SourceExpression">Source property to map</param>
        protected void Map(Expression<Func<Source, object>> SourceExpression)
        {
            Map(SourceExpression, "");
        }

        /// <summary>
        /// Maps source property
        /// </summary>
        /// <param name="SourceExpression">Source property to map</param>
        /// <param name="Format">Format string</param>
        protected void Map(Expression<Func<Source, object>> SourceExpression, string Format)
        {
            Setup();
            string SourceName = Utilities.Reflection.Reflection.GetPropertyName<Source>(SourceExpression);
            PropertyInfo SourceProperty = Utilities.Reflection.Reflection.GetProperty<Source>(SourceName);
            object[] Attributes = SourceProperty.GetCustomAttributes(typeof(Description), true);
            if (Attributes.Length > 0)
            {
                PropertyMappings.Add(new MappingInfo(SourceName, "", Format, ((Description)Attributes[0]).DescriptionValue));
            }
            else
            {
                PropertyMappings.Add(new MappingInfo(SourceName, "", Format, ""));
            }
        }

        #endregion

        #region Private Functions

        /// <summary>
        /// Sets up the mappings
        /// </summary>
        private void Setup()
        {
            if (PropertyMappings != null)
                return;
            SourceMapping = (TypeMapping)Manager.Instance.TypeMapping;
            PropertyMappings = new List<MappingInfo>();
        }

        #endregion

        #region Internal Properties

        internal TypeMapping SourceMapping { get; set; }
        internal List<MappingInfo> PropertyMappings { get; set; }

        #endregion
    }
}
